package com.sk.ccflower.server.match.xmlrpc;

import java.sql.Connection;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

import com.sk.ccflower.lib.commonUtils.ObjectUtil;
import com.sk.ccflower.lib.define.BaseCfg;
import com.sk.ccflower.lib.define.Consts;
import com.sk.ccflower.lib.pfBeans.ProfileBean;
import com.sk.ccflower.server.lib.dbBeans.CfProfileBean;
import com.sk.ccflower.server.lib.dbUtils.DBConnection;
import com.sk.ccflower.server.lib.dbUtils.qry.CfProfileQry;
import com.sk.ccflower.server.lib.sysUtils.MessageQueueUtil;
import com.sk.ccflower.server.match.MatchingCenter;

public class MatchingRobotThread extends Thread {
	
	private Logger m_log;
	private MatchingCenter m_parent = null;
	
	public MatchingRobotThread(MatchingCenter _parent) {
		this.m_log = Logger.getLogger( getClass() );
		this.m_parent = _parent;
	}
	
	private void startAllMatching() throws Exception {
		Connection conn = null;
		DBConnection dbConn = null;
		
		try {
			conn = m_parent.connectionPool.getConnection();
			dbConn = new DBConnection( conn );
			CfProfileQry pQry = new CfProfileQry( dbConn );
			pQry.select();
			
			for ( int i=0; i<pQry.m_arr.size(); i++ ) {
				CfProfileBean bean = (CfProfileBean) pQry.m_arr.get(i);
				ProfileBean pBean = new ProfileBean();
				ObjectUtil.objectCopy( pBean, bean, false );
				
				MessageQueueUtil.sendMsg( BaseCfg.MESSAGE_QUEUE_SERVER_URL, Consts.MESSAGE_QUEUE_NAME.MATCHING, pBean );
			}
		} catch ( Exception e ) {
			e.printStackTrace();
			this.m_log.error( e );
		} finally {
			if ( null != conn )		conn.close();
			if ( null != dbConn )	dbConn.close();
		}
	}
	
	public void run() {
		String[] cfgTime = BaseCfg.DAILY_MATCHING_TIME.split( ":" );
		int cfgHour = Integer.valueOf( cfgTime[0] );
		int cfgMin = Integer.valueOf( cfgTime[1] );
		long currTime = 0l;
		Calendar currDate = null;
		int currHour = 0;
		int currMin = 0;
		
		while ( true ) {
			try {
				currTime = System.currentTimeMillis();
				currDate = Calendar.getInstance();
				currDate.setTime( new Date(currTime) );
				currHour = currDate.get( Calendar.HOUR_OF_DAY );
				currMin = currDate.get( Calendar.MINUTE );
				
				if ( currHour == cfgHour ) {
					if ( currMin == cfgMin ) {
						m_log.debug( "MatchingRobotThread.startAllMatching() : START" );
						startAllMatching();
						m_log.debug( "MatchingRobotThread.startAllMatching() : END" );
					}
				}
				
				Thread.sleep( (10*1000) );
			} catch ( Exception e ) {
				e.printStackTrace();
				this.m_log.error( e );
			}
		}
	}
	
}
